package leetcode;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class LC19 {
    public static void main(String[] args) {
        LC19 lc19 = new LC19();
        lc19.spiralOrder(new int[][]{{1,2,3}});
        lc19.spiralOrder(new int[][]{{3},{4}});
        lc19.spiralOrder(new int[][]{{1,2,3},{4,5,6},{7,8,9}});
        lc19.spiralOrder(new int[][]{{2,5},{8,4},{0,-1}});
        lc19.spiralOrder(new int[][]{{1,2,3,4},{5,6,7,8},{9,10,11,12},{13,14,15,16},{17,18,19,20},{21,22,23,24}});
        lc19.spiralOrder(new int[][]{{1,2,3,4},{5,6,7,8},{9,10,11,12}});
    }
    public List<Integer> spiralOrder(int[][] matrix) {
        int left = 0,up = 0;
        int right = matrix[0].length - 1, down = matrix.length - 1;
        List<Integer> ans = new ArrayList<>();
        while(left <= right && up <= down){
            for (int i = left; i <= right; i++) {
                ans.add(matrix[up][i]);
            }
            for (int i = up+1; i <= down; i++) {
                ans.add(matrix[i][right]);
            }
            if (down > up && right > left) {
                for (int i = right - 1; i > left; i--) {
                    ans.add(matrix[down][i]);
                }
                for (int i = down; i > up; i--) {
                    ans.add(matrix[i][left]);
                }
            }
            left++;
            up++;
            right--;
            down--;
        }
        System.out.println(ans);
        return ans;
    }
    public List<Integer> spiralOrder1(int[][] matrix) {
        int l = matrix[0].length;
        int h = matrix.length;
        int hh = 0;
        int ll = 0;
        List<Integer> ans = new ArrayList<>();
        int i = l*h;
        int x = 1;
        while(i > 0){
            System.out.println(ans);
            ans.add(matrix[hh][ll]);
            matrix[hh][ll] = 0;
            if (x > 0) {
                if (ll + 1 < l && matrix[hh][ll + 1] != 0)
                    ll++;
                else if (hh + 1 < h && matrix[hh + 1][ll] != 0)
                    hh++;
                else
                    x = -1;
            }
            if (x < 0){
                if (ll - 1 >= 0 && matrix[hh][ll - 1] != 0)
                    ll--;
                else if (hh - 1 >= 0 && matrix[hh - 1][ll] != 0)
                    hh--;
                else {
                    x = 1;
                    ll++;
                }
            }
            --i;
        }
        System.out.println(Arrays.deepToString(matrix));
        System.out.println("---------");
        return ans;
    }
}
